import { useNavigate } from "react-router-dom";
import styles from './RightMask.module.css';
import { useSearchParams } from "react-router-dom";
export default function AnyMask(props) {
  const [SearchParams] = useSearchParams();
    const email = SearchParams.get('email');
  const navigate = useNavigate();
  const { maskid, maskName } = props;

  const generateUUID = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  };

  const handleClick = async () => {
    const sessionId = generateUUID();
    console.log("==========================" + sessionId);
    
    try {
      const sessionData = {
        id: sessionId,
        creatTime: new Date().toISOString(),
        lastUpdate: new Date().toISOString(),
        topic: `新的${maskName}对话`,
        mask: {
          id: maskid
        },
        email: email
      };

      const response = await fetch('http://localhost:5000/api/session/add', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(sessionData)
      });

      if (!response.ok) {
        throw new Error(`请求失败: ${response.status}`);
      }

      navigate(`/HeroSection/Chat?sessionId=${sessionId}&maskId=${maskid}&maskName=${maskName}&email=${email}`);
    } catch (error) {
      console.error('保存会话时出错:', error);
    }
  };

  return (
    <div 
      className={styles.anymask}
      onClick={handleClick}
      role="button"
      tabIndex={0}
      aria-label={`选择"${maskName}"面具，进入聊天页面`}
    >
      <div className={styles.maskIcon}>
        <i className="fa fa-user-secret"></i>
      </div>
      <span className={styles.maskName} >{maskName}</span>
    </div>
  );
}